<template>
	<view class="main" :style="{ bottom: `${vheight}rpx`, height: `${boxHeight}rpx` }">
		<view v-if="Object.keys(JoinUser).length > 0" class="animated-element">
			<image class="animated-imgs" :src="JoinUser.nicPic || '/static/none.png'" mode=""></image>
			<text class="animated-texts">{{ JoinUser.nicName }}</text>
			<text class="animated-texts">进来了</text>
		</view>
		<view class="change=line" :class="{ lineactive: isResizing }" @touchstart="startResize" @touchmove="onResize" @touchend="stopResize" @click="handerArea">
			<uni-icons size="28" type="up"></uni-icons>
		</view>

		<view class="chatarea">
			<scroll-view
				scroll-y="true"
				class="msgs"
				ref="msgs"
				:style="{ height: `${boxHeight - 140}rpx` }"
				scroll-with-animation="true"
				:scroll-into-view="viewId"
				:scroll-top="scrollTop"
				@scrolltoupper="loadMsgMore"
			>
				<view v-for="(item, index) in msglist" :key="index" :id="`msgall-${item.timestamp}`" @click="touchMain">
					<view class="timeformat" v-if="isTimeshow(index)">
						<view class="" style="background-color: rgba(0, 0, 0, 0.2)">
							<text style="font-size: 24rpx; color: #ffff00">{{ formatMessageTime(item.timestamp) }}</text>
						</view>
						<view v-if="senderLocation" class="" style="background-color: rgba(0, 0, 0, 0.2)">
							<text style="font-size: 24rpx; color: #ffff00">{{ formatDistance(item) }}</text>
						</view>
						<view v-else class="" style="background-color: rgba(0, 0, 0, 0.2)">
							<text style="font-size: 24rpx; color: #ffff00">定位中....</text>
						</view>
					</view>
					<view class="" style="display: flex;flex-direction: row;">
							<view class="msg" :class="item.userTel === user.userTel ? 'mymsg' : 'msg'">
						<img class="imgs" :src="item.nicPic || '/static/none.png'" mode="aspectFill" @click="handleNicPic(item)" />
						<view class="nicname-box">
							<text class="" style="color: #55ffff; font-size: 30rpx">{{ item.nicName || item.sendUserId }}:</text>
						</view>
						<view class="" v-if="item.messageType === 2">
							<text class="content-text" :style="{ color: 'white', 'font-size': '30rpx', 'font-weight': 600, 'max-width': isCardShow ? '450rpx' : '600rpx' }">
								{{ item.content.text }}
							</text>
						</view>
						<view class="" v-if="item.messageType === 1">
							<view class="progress-bar" :style="{ width: voiceWight(item.content.duration) + 'rpx' }" @click.stop="handonPlay(index)">
								<text style="color: white; font-size: 24rpx">
									{{ stateConfig.isplay === index ? progressPercent.toFixed(0) + '%' : '语音' + item.content.duration + '秒' }}
								</text>
								<view v-if="stateConfig.isplay === index" class="progress" :style="{ width: (voiceWight(item.content.duration) * progressPercent) / 100 + 'rpx' }">
									<uni-icons type="sound" size="26" color="#fff"></uni-icons>
								</view>
							</view>
						</view>
						<view class="" style="display: flex;flex-direction: row;" v-else-if="item.messageType === 3">
							<text class="mytext" style="color: yellow; font-size: 30rpx; white-space: normal" @click="handerPicShow(index)">图片信息</text>
							<uni-icons type="image" size="28" color="#00aaff" @click="handerPicShow(index)"></uni-icons>
						</view>
						<view class="" v-else-if="item.messageType === 6">
							<text class="mytext" style="color: yellow; font-size: 30rpx; white-space: normal">视频信息</text>
							<uni-icons type="videocam-filled" size="28" color="#00aaff" @click="handlevideoPath(item)"></uni-icons>
						</view>
	
					</view>
					<view v-if="!item.isSended" class="unsend" @click="reSendMsg(item)">
							<image class="unsend_img" src="/static/unsend.png" mode="aspectFit"></image>
					</view>
								
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="labellistx" v-if="labelShow">
			<scroll-view scroll-x class="scrollx">
				<view v-for="(item, key, index) in keytagObj()" :key="index" class="label-item" :class="{ activelabel: isChooseTag(key) }" @click="handerlabel(key, index)">
					<view class="label-item-img-box">
						<image class="label-item-img" :src="item.url" mode="aspectFill"></image>
					</view>
					<text style="font-size: 30rpx">{{ key }}</text>
				</view>
			</scroll-view>
		</view>
		<view v-show="!isInputShow" class="input-area">
			<view class="input">
				<view class="input-item" @click="handerinput"><text style="font-size: 35rpx">说点什么...</text></view>

				<uni-icons type="mic-filled" size="30" color="#ffaa00" @click="isSpeak = !isSpeak"></uni-icons>
			</view>

			<view class="inputimgs" @click="labelShow = !labelShow" :class="{ active: keytag().length > 0 }">
				<img class="inpimg" src="/static/tool/sendshop.png" mode="aspectFill" />
			</view>
			<view class="inputimgs" @click="chooseKeytag(['普通用户'], '用户')" :class="{ active: isChooseTag('普通用户') }">
				<img class="inpimg" src="/static/me.png" mode="aspectFill" />
			</view>
			<view class="inputimgs" @click="handleEnablePoi" :class="{ active: enablePoi }">
				<text style="color: white; font-size: 28rpx">POI</text>
			</view>
		</view>

	

		<markerInfo v-if="markerInfoShow" :userId="userInfo.targetId" :markerInfoShow="markerInfoShow" @close="markerInfoShow = false"></markerInfo>
		<goodShowCard :isCardShow="isCardShow" @CardShow="handleCardShow"></goodShowCard>
		<recordVioce class="recordVioce" @handleclose="isSpeak = false" @voice_msg="voice_msg" v-if="isSpeak"></recordVioce>
		<videoPlay :videoInfo="videoInfo" @closeVideo="closeVideo"></videoPlay>
		<!-- 	<MsgSlider :listData="msglist"></MsgSlider> -->
	</view>
</template>

<script>
import { webScoketMsg } from '../methods/handleWebSocketMessage';
import { initMsgData } from '../methods/initMsgData';
import { sendText, voiceMsg, mediaMsg, videoMsg, reSendMsg } from '../methods/msgSend.js';
import recordVioce from '../components/recordVioce.vue';
import formatMessageTime from '../utils/formatMessageTime.js';
import { formatDistance } from '../utils/distance.js';

import markerInfo from '../components/markerInfo.vue';
import goodShowCard from '../components/goodShowCard.vue';
import videoPlay from '../components/videoPlay.vue';
import { play } from '../methods/play';
import { keytag, shopIcon, keytagObj } from '../utils/shopIcon';
import { getPublicMsg, getGroupMsg, getPersonMsg } from '../utils/getMsgHistory';
import previewImageWithCache from '../utils/previewImageWithCache.js';

// import MsgSlider from '../components/MsgSlider.vue';
const app = getApp().globalData;
export default {
	components: {

		recordVioce,
		markerInfo,
		goodShowCard,
		videoPlay
		// MsgSlider
	},
	name: 'chatInMap',

	props: {
		keytags: {
			type: Array,
			default: () => []
		},
		maskerShow: {
			type: Boolean,
			default: false
		},

		enablePoi: {
			type: Boolean,
			required: true
		}
	},
	data() {
		return {
			stateConfig: {
				isSound: 1,
				isplay: -1,
				onPlay: false,
				isPlaying: false
			},
			viewId: '',
			isCardShow: false,
			senderLocation: null,
			progressPercent: 0,
			isVideoShow: false,
			vheight: 10,
			scrollTop: 0,
			isInputShow: false,
			isfocus: false,
			lastTimes: {},
			activelabel: -1,
			labelShow: false,
			isshopshow: true,
			markerInfoShow: false,
			playIndex: -1,
			JoinUser: {},
			targetId: '',
			toTarget: {
				targetType: '1',
				targetName: '公聊',
				targetId: ''
			},
			startY: 0,
			startHeight: 0,
			isResizing: false,
			height: 450,
			content: '',
			minHeight: 50,
			maxHeight: 1200,
			boxHeight: 400,
			messages: [],
			isSpeak: false,
			userInfo: {},
			user: {},
			page: {
				pages: 0,
				pageSize: 2
			},
			videoPath: '',
			videoFiles: {}, // 结构: { videoId: { tempPath, savedPath } }
			downloading: false,
			videoInfo: {}
		};
	},
	beforeDestroy() {
		uni.$off('msg');
		uni.$off('playIndex');
		uni.$off('location');
		uni.$off('isInputShow');
		uni.$off('voice');
		uni.$off('TouchEnd');
		uni.$off('public_msg');
		uni.$off('TouchMain');
		uni.$off('senderLocation');
	},

	created() {
		// uni.$on('TouchEnd', (res) => {
		// 	this.page.pages = 0;
		// 	this.getPublicMsg();
		// });
		// // uni.$on('public_msg', async (res) => {
		// // 	console.log('公共聊天信息', res);
		// // 	await webScoketMsg(this, res);
		// // });
		// uni.$on('playIndex', (res) => {
		// 	this.playIndex = res;
		// 	console.log(this.playIndex);
		// });

		// uni.$on('TouchMain', () => {
		// 	this.isInputShow = false;
		// });
		// uni.$on('senderLocation', (res) => {
		// 	this.senderLocation = res;
		// 	console.log('.....', this.senderLocation);
		// });
	},
	computed: {
		msglist() {
			return this.messages;
		}
	},

	mounted() {
		const storedFiles = uni.getStorageSync('VIDEO_FILES') || {};
		this.videoFiles = storedFiles;
		this.user = app.user;
		this.senderLocation = app.location;
		this.getPublicMsg();
		//	initMsgData(this);
	},
	watch: {
		msglist: {
			handler(newval) {
				console.log('newMsg',newval);
				app.locationMessage = newval;
				if (newval.length === 0) {
					this.boxHeight = 148;
				}
				this.$nextTick(() => {
					this.scrollTop += 10000;
				});
			}
		},

		isInputShow: {
			handler(newVal) {
				if (newVal) {
					this.vheight = 450;
				} else {
					this.vheight = 10;
				}
			}
		},

		location: {
			handler(newval) {
				console.log('位置变化', this.senderLocation);
				this.senderLocation = app.senderLocation;

				this.getPublicMsg();
			}
		}
	},
	methods: {
		//用于取商业类型函数
		keytag,
		keytagObj,
		handerArea() {
			if (this.boxHeight === 150) {
				this.boxHeight = 420;
			}
			if (this.boxHeight > 150) {
				this.boxHeight = 150;
			}
		},
		touchMain() {
			this.isInputShow = false;
		},
		startResize(e) {
			this.isResizing = true;
			this.startY = e.touches[0].pageY;
			this.startHeight = this.boxHeight;
			console.log('22', this.startY);
		},
		onResize(e) {
			if (!this.isResizing) return;

			const touch = e.touches[0];
			const newHeight = this.startHeight - (touch.pageY - this.startY);

			// 高度限制
			if (newHeight >= this.minHeight && newHeight <= this.maxHeight) {
				this.boxHeight = newHeight;
				this.chatHeight = this.chatHeight + touch.pageY;
				console.log(this.boxHeight);
			}
		},
		stopResize() {
			this.isResizing = false;
		},

		async getPublicMsg() {
			const res = await getPublicMsg(app.user, app.location);

			this.messages = res.data;
		},
		async handlevideoPath(item) {
			console.log(item);
			this.videoInfo = item;
		},
		closeVideo() {
			this.videoInfo = {};
		},
		voiceWight(times) {
			if (times < 2) {
				return 100;
			} else if (times > 60) {
				return 400;
			} else {
				return times * 5 + 100;
			}
		},
		handleCardShow(res) {
			this.isCardShow = res;
		},
		handleNicPic(item) {
			this.userInfo.targetId = item.sendUserId;
			this.userInfo.targetName = item.nicName;
			this.userInfo.nicPic = item.nicPic;
			this.markerInfoShow = true;
		},
		handleEnablePoi() {
			this.$emit('enablePoi');
		},
		handerPlay(item) {
			uni.$emit('voice', item);
		},
		handerPicShow(i) {
			previewImageWithCache(this.msglist[i].content.mediaPath);
		},
		handonPlay(i) {
			app.user.stateConfig.onPlay = !app.user.stateConfig.onPlay;
			if (!app.user.stateConfig.onPlay) {
				app.audioContext.stop();
				app.user.stateConfig.isPlaying = false;
			}
			if (app.user.stateConfig.onPlay) {
				play(this, i);
			}
		},
		handerlabel(item, index) {
			this.activelabel = index;
			this.$emit('chooseKeytag', [item]);
		},

		isChooseTag(item) {
			if (this.keytags.indexOf(item) === -1) {
				return false;
			} else {
				return true;
			}
		},

		handerinput() {
			this.isInputShow = true;
		},
		hangdleInputshow() {
			this.isInputShow = false;
			this.isSpeak = true;
		},
		chooseKeytag(keytag, type) {
			if (type === '商业') {
				this.labelShow = !this.labelShow;
			}

			this.$emit('chooseKeytag', keytag);
		},

		maskershow() {
			this.$emit('handerMarker');
		},

		async sendText(msg) {
			await sendText(this, msg);
		},
		//音频信息
		async voice_msg(voiceData) {
			voiceMsg(this, voiceData);
		},
		//图片信息
		async media_msg(mediapath) {
			mediaMsg(this, mediapath);
		},

		//视频信息
		async msg_video(item) {
			uni.showLoading({
				title: '视频上传中...'
			});
			const res = await videoMsg(this, item);
			if (res.data === 'ok') {
				uni.hideLoading();
			}
		},
		reSendMsg(item) {
			reSendMsg(item);
		},
		videoplay(url) {
			console.log('......', url);
			uni.navigateTo({
				url: `/pages/videoPlay/videoPlay?url=${url}`
			});
		},
		formatMessageTime,
		formatDistance,
		isTimeshow(index) {
			if (index > 0) {
				if (this.msglist[index].timestamp - this.msglist[index - 1].timestamp < 300000) {
					return false;
				} else if (!this.msglist[index].timestamp) {
					return false;
				} else {
					return true;
				}
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.main {
	position: fixed;
	left: 0rpx;
	bottom: 0rpx;
	z-index: 99;
	width: 750rpx;

	background: linear-gradient(to top, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.6));
	flex-direction: column;
	box-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
}
.animated-element {
	display: flex;
	position: absolute;
	top: 10rpx;
	left: 0;
	width: 100px;
	height: 30px;
	animation: leftToRight 3s linear both;
}
.animated-imgs {
	width: 32rpx;
	height: 32rpx;
	border-radius: 16rpx;
}
.animated-texts {
	font-size: 30rpx;
	color: #005500;
}
.change-line {
	width: 750rpx;
	height: 10rpx;
}
.lineactive {
	background: linear-gradient(to top, rgba(0, 85, 0, 0.8), rgba(255, 255, 255, 0.3));
}

.chatarea {
	display: flex;
	width: 700rpx;
	flex-direction: row;
}
.recordVioce {
	display: flex;
	flex-direction: row;
	position: absolute;

	align-self: center;
	justify-content: center;
	bottom: 10rpx;
}

.goodshow {
	width: 250rpx;
	height: 320rpx;
	border-radius: 15rpx;
	margin-left: 20rpx;
	margin-right: 20rpx;
	background-color: white;
	align-self: flex-end;
}

.msgs {
	display: flex;
	// justify-content: flex-end;
	flex-direction: column;
	margin-left: 10rpx;
	margin-right: 10rpx;
	width: 700rpx;
}

.msg {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	max-width: 600rpx;
	padding: 5rpx;
	margin: 5rpx;
	padding-left: 10rpx;
	margin-left: 20rpx;
	border-radius: 20rpx;
	align-items: center;
	background-color: rgba(0, 0, 0, 0.3);
	align-self: flex-start;

	/* 让元素靠左对齐 */
}
// .content-text {
//   display: -webkit-box;
//   -webkit-line-clamp: 3; /* 最多显示行数，可根据需求调整 */
//   -webkit-box-orient: vertical;
//   overflow: hidden;
//   text-overflow: ellipsis;
// }
.nicname-box {
	height: 32rpx;
	margin-left: 5rpx;
	margin-right: 5rpx;
	border-radius: 10rpx;
	background-color: #9a9a9a;
	box-shadow: 1rpx 1rpx 1rpx white;
}

.mytext {
	padding: 5rpx;
	border-radius: 4px;
	word-break: break-all;
	line-height: 45rpx;
	max-width: 500rpx;
}
.cardshow {
	max-width: 380rpx;
}

.mymsg {
	background-color: #5fbe00;
}

.input-area {
	display: flex;
	width: 750rpx;
	align-items: center;
	background-color: #000000;
	position: absolute;
	left: 0;
	bottom: 0;
	padding: 10rpx 20rpx;
	flex-direction: row;
	height: 90rpx;
	justify-content: space-between;
}

.active {
	background-color: #ffaa00;
}

.input {
	display: flex;
	flex-direction: row;
	height: 75rpx;
	width: 400rpx;
	justify-content: space-between;
	align-items: center;
	padding-left: 25rpx;
	padding-right: 10rpx;
	background-color: white;
	border-radius: 40rpx;
	box-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
}
.input-item {
	flex: 1;
}
.imgs {
	width: 40rpx;
	height: 40rpx;
	border-radius: 20rpx;
	background-color: white;
}
.unsend {
	display: flex;
	align-self: center;
	width: 120rpx;
	height: 30rpx;
	font-size: 28rpx;
	color: #333;

	
}
.unsend_img {
		width: 28rpx;
		height: 28rpx;
	}

.inputimgs {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 80rpx;
	height: 80rpx;
	border-radius: 40rpx;
	background-color: rgba(0, 0, 0, 0.2);
	box-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.inpimg {
	width: 60rpx;
	height: 60rpx;
	align-self: center;
	justify-self: center;
}

.inpimg1 {
	width: 80rpx;
	height: 80rpx;
	align-self: center;
	justify-self: center;
	border-radius: 40rpx;
}

.labellistx {
	display: flex;
	position: absolute;
	left: 0rpx;
	bottom: 100rpx;
	width: 750rpx;
	height: 80rpx;
	z-index: 1000;
}
.scrollx {
	display: flex;
	flex-direction: row;
	width: 750rpx;
	height: 80rpx;
}

.label-item {
	display: flex;
	flex-direction: row;
	margin: 10rpx;
	align-items: center;
	padding-left: 15rpx;
	padding-right: 15rpx;
	justify-content: center;
	min-width: 120rpx;
	height: 60rpx;
	box-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
	border-radius: 20rpx;
	background-color: #ffffff;
}
.label-item-img-box {
	width: 30rpx;
	height: 30rpx;
	margin-right: 10rpx;
}
.label-item-img {
	width: 30rpx;
	height: 30rpx;
}

.activelabel {
	background-color: #ffaa00;
}

.playbox {
	display: flex;
	flex-direction: row;
	align-items: center;
}

.timeformat {
	display: flex;
	flex-direction: row;
	justify-content: center;
	padding-right: 20rpx;
	width: 200px;
}
.progress-bar {
	display: flex;
	justify-content: center;
	height: 40rpx;
	border-radius: 10rpx;
	flex-direction: column;
	background-color: #ffaa00;
	align-items: center;
	font-size: 25rpx;
	color: #007bff;
	padding: 0;
	overflow: hidden;
}

.progress {
	align-self: self-start;
	background-color: #55ffff;
	height: 8rpx;
}
</style>
